#include "common.h"
#include <pthread.h>
#include <semaphore.h>

sem_t sem;

typedef struct _thread
{
	unsigned int num;
	int flag;
}thread_t;

void *producer(void *arg)
{
	thread_t *temp = (thread_t *)arg;
	sem_wait(&sem);
	static int test_flag;
	while(temp->flag == 0)
	{
		printf("There are %d products\n", temp->num);
		
		printf("Please input num <= %d\n", (10 - temp->num));
		scanf("%d", &temp->num);
		while(temp->num > 10)
		{
			printf("Please input again\n");
			scanf("%d", &temp->num);
		}

		temp->flag = 1;
		test_flag = temp->flag;
	}

	sem_post(&sem);
	sem_init(&sem, 0, 1);

	return &test_flag;
}

void *customer(void *arg)
{
	thread_t *temp = (thread_t *)arg;
	static int test_flag;
	//sem_post(&sem);
	sem_wait(&sem);
	while(temp->flag == 1)
	{
		printf("There are %d products\n", temp->num);
		int tp_num = temp->num;
		printf("How many products do you want, please input num < %d\n", temp->num);
		scanf("%d", &temp->num);
		while(temp->num > tp_num)
		{
			printf("Sorry, please input again\n");
			scanf("%d", &temp->num);
		}

		temp->flag = 0;
		test_flag = temp->flag;
	}

	sem_post(&sem);
	sem_init(&sem, 0, 1);

	return &test_flag;
}

int main()
{
	int ret = 0;
	pthread_t tid1, tid2;
	thread_t product = {0, 0};
	void *value = NULL;

	ret = sem_init(&sem, 0, 1);
	if(ret < 0)
		err_sys("sem_init error\n");

	while(product.flag == 1 || product.flag == 0)
	{
		if(product.num == 0 && product.flag == 1)
		{
			err_sys("warehouse is empty.\n");		
		}
		else if(product.num < 10 || product.flag == 0)
		{
			pthread_create(&tid1, NULL, producer, (void *)&product);
			continue;
		}
		else if((product.num > 0 && product.num <= 10) || product.flag == 1)
		{
			pthread_create(&tid2, NULL, customer, (void *)&product);
			continue;
		}
		else if(product.num == 10 && product.flag == 0)
		{
			err_sys("warehouse is full\n");
		}

		pthread_join(tid1, &value);
		pthread_join(tid2, &value);
		product.flag = *((int*)value);
	}


	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);

	sem_destroy(&sem);

	return 0;
}
